package com.ximu.order.controller;


import com.ximu.common_utlis.jwt.JwtUtil;
import com.ximu.common_utlis.result.Result;
import com.ximu.coupon.entity.Coupon;
import com.ximu.coupon.mapper.CouponMapper;
import com.ximu.order.entity.Order;
import com.ximu.order.mapper.OrderMapper;
import com.ximu.order.service.OrderService;
import com.ximu.order.vo.OrderVo;
import com.ximu.user.entity.User;
import com.ximu.user.mapper.UserMapper;
import com.ximu.user.service.AlipayService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ximu
 * @since 2023-03-18
 */
@RestController
@RequestMapping("/order")
@Api(tags = "我的订单接口")
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    @Qualifier("alipayService")
    private AlipayService alipayService;

    @ApiOperation(value = "查询用户订单")
    @PostMapping("findAllOrder")
    public Result findAllOrder(@RequestHeader("Authorization") String token) {

        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
//            QueryWrapper<Order> queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_id", Integer.parseInt(subject));
//            List<Order> orders = orderMapper.selectList(queryWrapper);
            List<OrderVo> allOrder = orderService.findAllOrder(Integer.parseInt(subject));
            return Result.ok().data("order", allOrder).message("成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("查询失败，检查是否登录");
    }

    @ApiOperation(value = "订单支付---有优惠券")
    @PostMapping("orderPayment")
    public Result orderPayment(@RequestHeader("Authorization") String token,@RequestParam(value = "orderId",required = true) int orderId,@RequestParam(value = "couponId",required = true) int couponId) {
        try {
            //获取id
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();

            //查询应该支付
            OrderVo oneOrder = orderMapper.findOneOrder(orderId);
            int orderAmount = oneOrder.getPaySum();
            //获取用户余额
            User user = userMapper.selectById(subject);
            BigDecimal userAmount = user.getBalance();
            //获取优惠金额
            Coupon coupon = couponMapper.selectById(couponId);
            Double couponAmount = coupon.getCouponAmount();

            if(orderAmount-couponAmount > userAmount.doubleValue()){
                return Result.error().message("余额不足");
            }else{
                double amount = userAmount.doubleValue() - (orderAmount - couponAmount);
                BigDecimal amounts = BigDecimal.valueOf(amount);
                user.setBalance(amounts);
                userMapper.updateById(user);
                coupon.setIsExchange(1);
                couponMapper.updateById(coupon);
                oneOrder.setOrderState(1);
                String pays = alipayService.appPagePay(String.valueOf(oneOrder.getOrderId()), (int) amount, oneOrder.getCarNum());
                int rs = orderMapper.updateOrder(oneOrder.getOrderState(),oneOrder.getOrderId());
                if (rs > 0) {
                    OrderVo order2 = orderMapper.findOneOrder(oneOrder.getOrderId());
                    return Result.ok().data("order", order2).message("支付成功").message("支付成功").data("三方支付结果",pays);
                } else {
                    return Result.error().message("支付失败，未知");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("支付失败，该订单已支付");
    }


    @ApiOperation(value = "订单支付---无优惠券")
    @PostMapping("orderPayment2")
    public Result orderPayment2(@RequestHeader("Authorization") String token,@RequestParam(value = "orderId",required = true) int orderId) {
        try {
            //获取id
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();

            //查询应该支付
            OrderVo oneOrder = orderMapper.findOneOrder(orderId);
            int orderAmount = oneOrder.getPaySum();
            //获取用户余额
            User user = userMapper.selectById(subject);
            BigDecimal userAmount = user.getBalance();
            if(orderAmount > userAmount.doubleValue()){
                return Result.error().message("余额不足");
            }else{
                double amount = userAmount.doubleValue() - orderAmount;
                BigDecimal amounts = BigDecimal.valueOf(amount);
                user.setBalance(amounts);
                userMapper.updateById(user);
                oneOrder.setOrderState(1);
                String pays = alipayService.appPagePay(String.valueOf(oneOrder.getOrderId()), (int) amount, oneOrder.getCarNum());
                int rs = orderMapper.updateOrder(oneOrder.getOrderState(),oneOrder.getOrderId());
                if (rs > 0) {
                    OrderVo order2 = orderMapper.findOneOrder(oneOrder.getOrderId());
                    return Result.ok().data("order", order2).message("支付成功").data("三方支付结果",pays);
                } else {
                    return Result.error().message("支付失败，未知");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("支付失败，该订单已支付");
    }

    @ApiOperation(value = "新增订单")
    @PostMapping("addOrder")
    public Result addOrder(@RequestHeader("Authorization") String token, @RequestBody Order order) {
        try {
            //获取id
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            order.setOrderId(null);
            order.setUserId(Integer.valueOf(subject));
            order.setCarId(order.getCarId());
            order.setOrderDate(null);
            order.setOrderState(0);
            order.setPaySum(order.getPaySum());
            order.setPayDate(null);

            int rs = orderMapper.insertOrder(order.getUserId(),order.getCarId(),order.getPaySum());
            if (rs > 0) {
                List<OrderVo> allOrder = orderService.findAllOrder(Integer.parseInt(subject));
                return Result.ok().data("order", allOrder).message("订单新增成功");
            } else {
                return Result.error().message("订单新增失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error().message("订单新增失败");
    }

}

